#include "C_ObjectManager.h"
#include "VBF_Common/VBF_Math/VBF_TimeConverter.h"
#include "VBF_Base/IVBF_SimulationTimer.h"
#include "C_JD2Unix.h"
#include "string"
using namespace std;
#include "datasource/C_DBDataSourceFactory.h"
using namespace onegis::psde::datasource;

extern const string SERVER;
extern const string DS;
extern string USER;
extern string PASSWORD;

C_ObjectManager* C_ObjectManager::m_pObjectManager = NULL;
C_ObjectManager::C_ObjectManager(void)
{
}


C_ObjectManager::~C_ObjectManager(void)
{
	clearObjectData();

	if(m_pObjectManager != NULL)
		delete m_pObjectManager;
	m_pObjectManager = NULL;
}

C_ObjectManager* C_ObjectManager::getInstance()
{
	if(m_pObjectManager == NULL)
		m_pObjectManager = new C_ObjectManager;
	return m_pObjectManager;
}

PbSObject* C_ObjectManager::getCurrentObjById( const long long& lId )
{
	double dCurrent = VBF_GetSimulationTimer()->GetDDayTimeCurrent();
	long long lUnixMS = C_JD2Unix::JD2Unix(dCurrent) * 1000;
	MapVersion mapVersion = m_mapObject[lId];
	PbSObject* pObject = NULL;
	for (MapVersion::Iterator it = mapVersion.begin(); it!= mapVersion.end(); it++)
	{
		if(lUnixMS >= it.key())
			pObject = it.value();
	}
	return pObject;
}

QVector<PbSObject*> C_ObjectManager::getAllVersionsById( const long long& lId )
{
	QVector<PbSObject*> vecObj;
	if(!m_mapObject.contains(lId))
		return vecObj;

	MapVersion mapVersion = m_mapObject[lId];
	for (MapVersion::Iterator it = mapVersion.begin(); it != mapVersion.end(); it++)
	{
		vecObj.push_back(it.value());
	}
	return vecObj;
}


int C_ObjectManager::loadObjectVersions( const long long& lId, const PbSObjects& objS )
{
	int objCount = objS.sobjects().size();
	if(objCount == 0)
		return 0;
	MapVersion mapVersion;
	for (int i = 0;i<objCount;i++)
	{
		PbSObject* pObject = new PbSObject(objS.sobjects(i));
		mapVersion.insert(pObject->realtime(),pObject);
	}
	m_mapObject.insert(lId, mapVersion);
	return mapVersion.size();
}

bool C_ObjectManager::isObjectLoaded( const long long& lId )
{
	if(m_mapObject.contains(lId))
		return true;
	else
		return false;
}

void C_ObjectManager::clearObjectData()
{
	QMap<long long, MapVersion>::iterator itObj;
	for (itObj = m_mapObject.begin(); itObj != m_mapObject.end(); itObj++)
	{
		MapVersion mapVersion = itObj.value();
		MapVersion::iterator itVersion;
		for (itVersion = mapVersion.begin(); itVersion != mapVersion.end(); itVersion++)
		{
			PbSObject* pObject = itVersion.value();
			delete pObject;
			pObject = NULL;
		}
		mapVersion.clear();
	}
	m_mapObject.clear();
}

void C_ObjectManager::onEmitObjectSelected( QVector<PbSObject*> vecObj)
{
	emit objectSelected(vecObj);
}

void C_ObjectManager::onEmitObjectLoaded( QVector<PbSObject*> vecObj)
{
	emit objectLoaded(vecObj);
}
